using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Microsoft.JScript;


/// <summary>
/// Summary description for PageControlEvents
/// </summary>
public class PageControlEvents
{

    string strsendercontrolid = "";
	public PageControlEvents()
	{
		//
		// TODO: Add constructor logic here
		//
	}

    public void DoControlEvents(HtmlForm frmobj,DataSet dsepageinfo)
    {
        if (dsepageinfo.Tables["ControlEvents"] != null)
        {
            if (dsepageinfo.Tables["ControlEvents"].Rows.Count > 0)
            {
                foreach (DataRow dr in dsepageinfo.Tables["ControlEvents"].Rows)
                {
                    string targetid = dr["target_control"].ToString();
                    string expression = dr["expression"].ToString();
                    string sourceid = dr["source_control"].ToString();

                    bool blnmultiplerecordpage = false;
                    int rowcount = 0;

                    string page_id = dsepageinfo.Tables["Page"].Rows[0]["page_id"].ToString();

                    blnmultiplerecordpage = System.Convert.ToBoolean(dsepageinfo.Tables["Page"].Rows[0]["multiple_recs_page"].ToString());

                    if (blnmultiplerecordpage)
                    {
                        HtmlInputHidden hihObj = (HtmlInputHidden)FindControl(frmobj.Controls, "_sys" + page_id + "_RowCount");
                        rowcount = System.Convert.ToInt32(hihObj.Value);
                    }

                    if (strsendercontrolid != "")
                    {
                        if (dr["event_type"].ToString().ToLower() == "sv")
                        {
                            int controlrowcount = 0;

                            if (blnmultiplerecordpage)
                            {
                                try
                                {
                                    string strrowcount = strsendercontrolid.Substring(strsendercontrolid.LastIndexOf("_") + 1);
                                    controlrowcount = System.Convert.ToInt32(strrowcount);
                                }
                                catch
                                {
                                    controlrowcount = 1;
                                }
                            }

                            if (!isEditOrCopyMode())
                                assignControlEventValue(frmobj, expression, targetid, controlrowcount, dsepageinfo, page_id, blnmultiplerecordpage);
                        }
                    }
                    else
                    {


                        for (int i = 0; i <= rowcount; i++)
                        {
                            if (dr["event_type"].ToString().ToLower() == "sv")
                            {
                                if (!isEditOrCopyMode())
                                    assignControlEventValue(frmobj, expression, targetid, i, dsepageinfo, page_id, blnmultiplerecordpage);
                            }
                        }
                    }



                }
            }
        }

    }
    private bool isEditOrCopyMode()
    {
        try
        {
            return HttpContext.Current.Request.Url.ToString().ToLower().IndexOf("&cpy=0") > 0 || HttpContext.Current.Request.Url.ToString().ToLower().IndexOf("&pk=") > 0;
        }
        catch (Exception e)
        {
            return false;
        }
    }
    private void assignControlEventValue(HtmlForm frmobj, string expression, string target, int rowcount, DataSet dsepageinfo,string page_id,bool blnmultiplerecspage)
    {
        string result =getCorrectExpression(frmobj,expression, rowcount, page_id,dsepageinfo);
        //if (result == "") return;
        string targetcontrolid = page_id + "_" + target;
        if (blnmultiplerecspage)
        {
            targetcontrolid = page_id + "_" + target + "_" + rowcount;
        }

        Control con = FindControl(frmobj.Controls, targetcontrolid);
        if (con != null)
        {
            if (con is TextBox)
            {
                TextBox textobj = (TextBox)con;
                textobj.Text = result;
            }
            if (con is DropDownList)
            {
                DropDownList dropdownobj = (DropDownList)con;
                dropdownobj.SelectedValue = result;
            }
        }


    }

    private string getCorrectExpression(HtmlForm frmobj,string expression,int rowcount,string page_id,DataSet dsepageinfo)
    {
        string[] splitexpression = null;
        string result = "";
        if (expression != "")
        {
            splitexpression = expression.Split('$');
        }
        splitexpression = ReplaceExpressionIds(splitexpression, rowcount, page_id,dsepageinfo);

        for (int i = 0; i < splitexpression.Length; i++)
        {
            result = result+getcontrolvalue(frmobj,splitexpression[i]);
        }

       // double doubleresult = 0;

       //doubleresult = getresultfromexpression(result);
        string strResult = "";
        strResult = getresultfromexpression(result);


        return strResult.ToString();


    }

    private string getresultfromexpression(string expression)
    {
        string result = "";
        string[] splitedexpression = null;
        string[] symbols = { "+", "-", "*", "/", "\\", "%" };
             

        string myobj = calcExpression(expression);

        return myobj;
    }

    private string[] ReplaceExpressionIds(string[] splitexpression, int rowcount,string page_id,DataSet dsepageinfo)
    {
        if (splitexpression.Length > 0)
        {
            for (int i = 0; i < splitexpression.Length; i++)
            {
                if (splitexpression[i] != "")
                {
                    string controlid="";
                    DataRow[] datarow = dsepageinfo.Tables["PageCtrl"].Select("control_id = '"+splitexpression[i].Replace("'","''")+"'");
                    if(datarow.Length>0)
                    {
                        controlid = datarow[0]["control_id"].ToString();
                    }
                    if(controlid!="")
                    {
                        if (rowcount == 0)
                        {
                            splitexpression[i] = page_id + "_" + controlid;
                        }
                        else
                        {
                            splitexpression[i] = page_id + "_" + controlid + "_" + rowcount;
                        }

                    }
                }
            }
        }
        return splitexpression;
    }

    private string getcontrolvalue(HtmlForm frmobj,string controlid)
    {
        string result = controlid;
        Control con = FindControl(frmobj.Controls, controlid);

        if (con != null)
        {
            if (con is TextBox)
            {
                TextBox textobj = (TextBox)con;
                result = textobj.Text;
            }
            if (con is DropDownList)
            {
                DropDownList DropDownObj = (DropDownList)con;
                result = DropDownObj.SelectedValue;
            }
        }

        return result;
    }


    public Control FindControl(ControlCollection frmControl, string strControlId)
    {
        Control cRet = null;
        foreach (Control con in frmControl)
        {
            if (con.ID != null)
                if (con.ID.ToLower() == strControlId.ToLower())
                    return con;
        }

        foreach (Control cn in frmControl)
            if (cn.Controls.Count > 0)
            {
                cRet = FindControl(cn.Controls, strControlId);
                if (cRet != null) break;
            }
        return cRet;
    }


/// <summary>
/// Calculates the String Expression using JScript function. creatd by sanal on 31 July 2007
/// </summary>
/// <param name="Expression">The expression to be evaluated</param>
/// <returns>Returns an Object as result. Returns null if error</returns>
private string calcExpression(string Expression)
{
    string ret = "";
    try
    {
        if (Expression == "")
            ret = "";
        else
            ret = Microsoft.JScript.Convert.ToNumber(Microsoft.JScript.Eval.JScriptEvaluate(Expression, Microsoft.JScript.Vsa.VsaEngine.CreateEngine())).ToString();
        if (ret == "NaN")
            ret = "";
    }
    catch (Exception ee)
    {

    }
    return ret;
}

    public void DoControlEvents(HtmlForm frmobj, DataSet dsepageinfo,string sendercontrolid)
    {
        if (dsepageinfo.Tables["ControlEvents"] != null)
        {
            if (dsepageinfo.Tables["ControlEvents"].Rows.Count > 0)
            {
                strsendercontrolid = sendercontrolid;
                DoControlEvents(frmobj, dsepageinfo);
            }
        }

    }


}
